<!--公司公告-消息管理 NoticeMessage-->
<template>
  <div class='page_format'>
    <div class="my_Select">
      <el-form :inline="true" class="search-form" style="display: flex; align-items: center; flex-wrap: wrap;">
        <el-form-item>
          <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <el-button class="bt-color-tjd" type="primary"  style="margin-right: 10px;"
                     v-if="is_show_button('button_message_save')"
                     @click="saveDataForm">添加
          </el-button>
          <el-button v-if="is_show_button('competence_message_publish_all') || is_show_button('competence_message_publish_part')" class="bt-color-tjd" type="primary"
                     style="margin-right: 10px;" @click="changeStatus(1)" >发布</el-button>
          <el-button v-if="is_show_button('competence_message_publish_all') || is_show_button('competence_message_publish_part')" class="bt-color-tjd" type="primary"  style="margin-right: 10px;"
                     @click="changeStatus(2)" >取消发布</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-form-item>
            <el-select style="width: 110px;" v-model="noticeColumnId" placeholder="公告栏目" size="small" clearable
                       @change="handleQuery">
              <el-option
                  v-for="(item, index) in noticeColumnList"
                  :key="index"
                  :label="item.name"
                  :value="item.noticeColumnId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select style="width: 110px;" v-model="queryStatus" placeholder="发布状态" size="small" clearable
                       @change="handleQuery">
              <el-option
                  v-for="(item, index) in statusData"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-input style="width:140px;margin-right:8px" size="small" placeholder="标题" v-model="queryValue"
                    clearable></el-input>
          <el-button size="small" @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="list" border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="40" align="center"></el-table-column>-->
      <el-table-column type="selection" width="40" align="center"
                       :selectable="checkSelectable">
      </el-table-column>
      <el-table-column type="index" :index="sort" label="序号" width="50"></el-table-column>
      <el-table-column prop="noticeId" label="ID"></el-table-column>
      <el-table-column prop="titleZh" label="标题"></el-table-column>
      <el-table-column prop="shape" label="公告栏目" align="center">
        <template v-slot="scope">
          <span>{{ getNoticeColumnText(scope.row.noticeColumnId) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="receiveObjectValue" label="接收对象">
        <template v-slot="scope">
    <span v-if="scope.row.receiveObjectType === '0'">
      {{ getReceiveObjectValueText(scope.row) }}
    </span>
          <span v-else>按人员-
      <!-- 设置蓝色字体并添加鼠标样式 -->
      <span
          @click="showUserDetails(scope.row.receiveObjectValue)"
          style="color: #1890ff; cursor: pointer; text-decoration: underline;">
        查看详情
      </span>
    </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template v-slot="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="发布人员">
        <template v-slot="scope">
          <span>{{ getUserNameText(scope.row.createBy) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template v-slot="scope">
          <el-button @click="handleView(scope.row)" type="text" size="small">
            {{ '查看' }}
          </el-button>
          <el-button v-if="is_show_button('competence_message_delete_all') ||
           (is_show_button('competence_message_delete_part') && scope.row.createBy === currentUserId)" @click="handleClick(scope.row)" type="text" size="small">
            {{ '编辑' }}
          </el-button>
          <el-button
            v-if="is_show_button('competence_message_delete_all') ||
           (is_show_button('competence_message_delete_part') && scope.row.createBy === currentUserId)"
            @click="handleButtonClick(scope.row)"
            type="text"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="form.noticeId ?'修改':'添加'" :visible.sync="dialogFormVisible" center @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="消息栏目：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="noticeColumnId">
          <el-select v-model="form.noticeColumnId" placeholder="请选择消息栏目" style="width: 50%;">
            <el-option
                v-for="item in noticeColumnList"
                :key="item.noticeColumnId"
                :label="`${item.name}`"
                :value="item.noticeColumnId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息标题：" :label-width="formLabelWidth" prop="titleZh">
          <el-input v-model="form.titleZh" placeholder="请输入消息标题" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="接收对象：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;" prop="receiveObjectType">
          <el-select v-model="form.receiveObjectType" placeholder="请选择接收对象" style="width: 50%;">
            <el-option
                v-for="item in receiveObjectTypeData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="receiveObjectType">
          <el-select v-if="form.receiveObjectType === '0'" v-model="form.receiveObjectValue" placeholder="请选择品类"
                     style="width: 50%;">
            <el-option
                v-for="item in deviceKindData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
          <el-cascader v-else v-model="userCascadeList"
                       placeholder="请选择接收人员" style="width: 50%;" multiple
                       :options="userCascadeData"
                       :props="{ multiple: true, emitPath: false }"
                       :show-all-levels="false"
                       filterable></el-cascader>
        </el-form-item>

      <el-form-item label="消息内容" :label-width="formLabelWidth"  prop="receiveObjectType">
        <wang-editor :height="350" @OnChange="editorChange" ref="wangEditor"/>
      </el-form-item>
<!--      <el-form-item label="消息内容(英)：" :label-width="formLabelWidth">-->
<!--        <wang-editor :height="350" @OnChange="editorChangeEn" ref="wangEditorEN"/>-->
<!--      </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('button_message_save')" type="primary"
                   @click="saveDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗部分 -->
    <el-dialog title="人员详情" :visible.sync="userDetailsDialogVisible" width="30%">
      <el-table :data="userDetails" style="width: 100%">
        <el-table-column prop="companyName" label="公司名称"></el-table-column>
        <el-table-column prop="nickName" label="人员昵称"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button @click="userDetailsDialogVisible = false">关闭</el-button>
  </span>
    </el-dialog>

    <el-dialog :title="`批量${status < 1?'删除':(status === 1?'发布': '取消发布')}`"
               :visible.sync="changShow" center width="400px">
      <span style="display: inline-block; width: 100%; text-align: center; padding: 2px 0;"
            v-for="(item, index) in changeList" :key="index">
        {{ item.titleZh }} <br>
      </span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changShow = false">取 消</el-button>
        <el-button class="bt-color-tjd" type="primary" @click="saveStatusDataApi" :loading="batchLoading">确 定</el-button>
      </div>
    </el-dialog>
    <Toast :dialogVisible="dialogVisible" @isDelete="deleteDataApi"></Toast>
  </div>
</template>

<script>

import wangEditor from '@/components/wangEditor/index.vue'
import { post } from '@/api/my_axios'
import { changSort } from '@/utils/aqi'

export default {
  name: '',
  data () {
    return {
      batchLoading: false,
      changShow: false,
      userDetailsDialogVisible: false, // 弹窗显示状态
      userDetails: [], // 弹窗中展示的用户详情数据
      submitLoading: false, // 按钮loading
      dialogFormVisible: false,
      dialogVisible: false,
      form: {
        noticeId: '',
        noticeColumnId: '',
        titleZh: '',
        titleEn: '',
        contentUrlZh: '',
        contentUrlEn: '',
        status: '',
        receiveObjectType: '',
        receiveObjectValue: '',
        remark: ''
      },
      richTextDTO: { // 富文本编辑
        richTextUrlZh: '',
        richTextUrlEn: ''
      },
      list: [],
      noticeColumnList: [],
      deviceKindData: [],
      userCascadeData: [],
      userCascadeList: [],
      selectedUserDetails: [],
      multipleSelection: [], // 多选
      changeList: [], // 多选
      contentTextZh: '',
      contentTextEn: '',
      status: '',
      formLabelWidth: '140px',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      id: '',
      queryValue: '',
      queryStatus: '',
      noticeColumnId: '',
      rules: {
        noticeColumnId: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        titleZh: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        receiveObjectType: [{ required: true, message: '必填项不能为空！', trigger: 'change' }]
      },
      statusData: [
        { value: '0', label: '未发布' },
        { value: '1', label: '发布中' },
        { value: '2', label: '已失效' }
      ],
      receiveObjectTypeData: [
        { value: '0', label: '按品类' },
        { value: '2', label: '按人员' }
      ]
    }
  },

  mounted () {
    this.getDictSortData()
    this.getNoticeColumnList()
    this.getNoticeList()
    this.getUserCascadeRelation()
  },

  components: {
    wangEditor
  },

  computed: {
    currentUserId () {
      // 假设用户 ID 存在 Vuex 里
      return this.$store.state.module1.UserInfo.userName
    }
  },

  watch: {
    'form.receiveObjectType' (newValue) {
      if (newValue === '0') {
        this.userCascadeList = [] // 清空接收人员
      } else {
        this.receiveObjectValue = '' // 清空品类
      }
    }
  },

  methods: {
    // 排序 （序号）
    sort (index) {
      return changSort(index, this.pageNum, this.pageSize)
    },

    // 校验部分权限
    checkSelectable (row) {
      const canPublishAll = this.is_show_button('competence_message_publish_all')
      const currentUser = this.$store.state.module1.UserInfo.userName // 假设当前用户信息存储在 Vuex

      // 有 "competence_message_publish_all" 权限的人可以选所有
      if (canPublishAll) return true

      // 没有权限的人，只能选自己创建的
      return row.createBy === currentUser
    },

    showUserDetails (receiveObjectValue) {
      // 分割 receiveObjectValue 获取 userName 列表
      const userNames = receiveObjectValue.split(',')

      // 根据 userNames 查询 companyName 和 nickName
      const userDetails = []
      this.userCascadeData.forEach(company => {
        company.children.forEach(user => {
          if (userNames.includes(user.value)) {
            userDetails.push({
              companyName: company.label,
              nickName: user.label
            })
          }
        })
      })

      // 更新弹窗数据并显示
      this.userDetails = userDetails
      this.userDetailsDialogVisible = true
    },

    // 接收对象
    getReceiveObjectValueText (value) {
      if (value.receiveObjectType === '0') {
        const dto = this.deviceKindData.find(v => v.value === value.receiveObjectValue)
        return `按品类-${dto?.label || '未知'}`
      } else {
        return '按人员-查看详情'
      }
    },

    // 用户名转化
    getUserNameText (value) {
      // 遍历 userCascadeData，查找匹配的 userName，并返回对应的 nickName
      for (const manager of this.userCascadeData) {
        const user = manager.children.find(child => child.value === value)
        if (user) {
          return user.label // 返回对应的 nickName
        }
      }
      return '' // 如果未找到，返回空字符串
    },

    // 公告栏目
    getNoticeColumnText (value) {
      const dto = this.noticeColumnList.find(v => v.noticeColumnId === value)
      return dto ? dto.name : '未知栏目'
    },

    // 状态
    getStatusText (value) {
      const dto = this.statusData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    changeStatus (status) {
      if (this.multipleSelection.length < 1) {
        this.$message.error('请先选择数据！')
        return
      }
      this.changShow = true
      this.changeList = this.multipleSelection
      this.status = status
    },

    // 新增
    saveDataForm () {
      this.dialogFormVisible = true
      this.form.receiveObjectType = '0'
      this.form.status = '0'
      this.userCascadeList = []
    },

    // 富文本编辑
    editorChange (val) {
      if (val === '<p><br></p>') {
        this.contentTextZh = ''
        return
      }
      this.contentTextZh = val
    },
    editorChangeEn (val) {
      if (val === '<p><br></p>') {
        this.contentTextEn = ''
        return
      }
      this.contentTextEn = val
    },

    handleView (row) {
      // 固定的 baseUrl
      const baseUrl = 'https://tjd-system-oss.ss-tjd.com/dev/htmlUrl/RichTextCrmNotice.html?src='

      // 校验并获取 contentUrlZh
      const contentUrlZh = row.contentUrlZh ? row.contentUrlZh : ''
      if (!contentUrlZh) {
        this.$message.error('内容链接无效')
        return
      }

      // 校验并获取 titleZh
      const titleZh = row.titleZh ? row.titleZh : '消息公告'
      const encodedTitle = encodeURIComponent(titleZh) // URL 编码

      // 获取当前时间并格式化为 YYYY-MM-DD HH:mm:ss
      const currentTime = row.createTime
      const encodedTime = encodeURIComponent(currentTime) // URL 编码

      // 拼接完整 URL，增加 time 参数
      const targetUrl = `${baseUrl}${contentUrlZh}&title=${encodedTitle}&time=${encodedTime}`

      // 打开新页面
      try {
        window.open(targetUrl, '_blank')
      } catch (error) {
        console.error('跳转失败:', error)
        this.$message.error('跳转失败，请重试')
      }
    },

    // 修改
    handleClick (row) {
      this.dialogFormVisible = true
      Object.keys(row).forEach(key => {
        this.form[key] = row[key]
      })
      this.userCascadeList = []
      if (row.receiveObjectType === '2' && row.receiveObjectValue) {
        this.userCascadeList = row.receiveObjectValue.split(',')
      }

      // 判断 URL 是否不为空且带有 .txt 的后缀
      const isValidZhUrl = row.contentUrlZh && row.contentUrlZh.endsWith('.txt')
      const isValidEnUrl = row.contentUrlEn && row.contentUrlEn.endsWith('.txt')

      Promise.all([
        isValidZhUrl ? fetch(row.contentUrlZh) : Promise.resolve(null),
        isValidEnUrl ? fetch(row.contentUrlEn) : Promise.resolve(null)
      ]).then(res => {
        if (isValidZhUrl && res[0]) {
          res[0].text().then(text => {
            this.contentTextZh = text
            this.$refs.wangEditor.SetPreContent(text)
          })
        }
        if (isValidEnUrl && res[1]) {
          res[1].text().then(text => {
            this.contentTextEn = text
            this.$refs.wangEditorEN.SetPreContent(text)
          })
        }
      })
        .finally(() => {
          this.editLoading = false
        })
    },

    // 关闭dialog框
    closeDialog () {
      this.batchLoading = false
      this.changShow = false
      this.dialogFormVisible = false
      this.submitLoading = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.userCascadeList = []
      this.contentTextZh = ''
      this.contentTextEn = ''
      this.status = ''
      if (this.contentTextZh) this.$refs.wangEditor.ClearContent()
      if (this.contentTextEn) this.$refs.wangEditorEN.ClearContent()
      this.$refs.wangEditor.ClearContent()
      this.$refs.dialogForm.resetFields()
    },

    getNoticeList () {
      this.list = []
      this.$store.dispatch('getNoticeList', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        queryValue: this.queryValue,
        noticeColumnId: this.noticeColumnId,
        status: this.queryStatus
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },

    saveDataApi () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        if (this.contentTextZh) this.form.contentTextZh = this.contentTextZh
        if (this.contentTextEn) this.form.contentTextEn = this.contentTextEn
        if (Array.isArray(this.userCascadeList) && this.userCascadeList.length > 0) {
          this.form.receiveObjectValue = this.userCascadeList.toString()
        }
        this.submitLoading = true
        post('/api/crm/sys/manage/notice/saveInfo', this.form).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
          } else {
            this.$message({ message: req.msg, type: 'error' })
          }
        }).finally(() => {
          this.closeDialog()
          this.getNoticeList()
        })
      })
    },

    saveStatusDataApi () {
      const params = {
        noticeIdList: [],
        saveType: 2,
        status: ''
      }
      this.multipleSelection.forEach(v => {
        params.noticeIdList.push(v.noticeId)
      })
      params.status = this.status
      this.batchLoading = true
      post('/api/crm/sys/manage/notice/saveInfo', params).then(req => {
        if (req && req.code === 200) {
          this.$message({ message: '成功！', type: 'success' })
        } else {
          this.$message({ message: '失败！', type: 'error' })
        }
      }).finally(() => {
        this.getNoticeList()
        this.closeDialog()
      })
    },

    deleteDataApi (type) {
      if (type === 'ok') {
        post('/api/crm/sys/manage/notice/deleteById', this.id
        ).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
            this.getNoticeList()
          }
        })
      }
      this.dialogVisible = false
    },

    getNoticeColumnList () {
      this.$store.dispatch('getNoticeColumnList', {
        pageSize: 1000,
        pageNum: 1
      }).then(res => {
        this.noticeColumnList = res.data
      })
    },

    // 数据字典配置分类项获取
    getDictSortData (type) {
      // 项目品类
      this.$store.dispatch('getSysDictItemList', 'deviceKind').then(res => {
        this.deviceKindData = res
      })
    },

    // 用户级联关系
    getUserCascadeRelation () {
      this.$store.dispatch('getUserCascadeRelation').then(res => {
        const array = []
        res.forEach(item => {
          if (item.userInfoVOList && item.userInfoVOList.length) {
            array.push({
              value: item.firstLevelId,
              label: item.firstLevelName,
              children: item.userInfoVOList.map(item1 => {
                // 建立 userName 和公司名之间的映射关系
                return {
                  value: item1.userName,
                  label: item1.nickName
                }
              })
            })
          }
        })
        this.userCascadeData = array
      })
    },

    handleSelectionChange (val) {
      this.multipleSelection = val
    },

    handleQuery () {
      this.pageNum = 1
      this.getNoticeList()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.getNoticeList()
    },

    handleCurrentChange (val) {
      this.pageNum = val
      this.getNoticeList()
    },

    handleButtonClick (data) {
      this.id = data.noticeId
      this.dialogVisible = true
    },

    is_show_button (name) {
      let show = false
      this.$store.state.module1.menu_list.forEach(v => {
        // eslint-disable-next-line eqeqeq
        if (v.path === name) {
          show = true
        }
      })
      return show
    }
  }
}
</script>

<style lang='scss'>
.page_format {
  padding: 56px 20px 140px 20px;
}

.search-form {
  margin-top: 10px;
}

.icon-image {
  width: auto;
  height: auto;
  object-fit: cover;
}
</style>
